//
//  SureOrderViewController.m
//  Findif
//
//  Created by Mac on 2018/11/2.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "SureOrderViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "WXApiRequestHandler.h"
#import "WXApi.h"
//首先导入头文件信息
#include <ifaddrs.h>
#include <arpa/inet.h>
//#include <net/if.h>
#import "WXApiManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import "NewCouponTableViewCell.h"
#import "SureUserCouponModel.h"
#import "MyOrderViewController.h"
#import "MapViewController.h"
#import "GroupActiveViewController.h"

//#define IOS_CELLULAR    @"pdp_ip0"
//#define IOS_WIFI        @"en0"
////#define IOS_VPN       @"utun0"
//#define IP_ADDR_IPv4    @"ipv4"
//#define IP_ADDR_IPv6    @"ipv6"

@interface SureOrderViewController ()<UITableViewDelegate,UITableViewDataSource,WXApiManagerDelegate>

@property (nonatomic, strong)UIView * topView;
@property (nonatomic, weak)UIImageView * iconImageView;
@property (nonatomic, weak)UILabel * shopNameLabel;
@property (nonatomic, weak)UIImageView * goodsImageView;
@property (nonatomic, strong)UILabel * goodsNameLabel;
@property (nonatomic, strong)UILabel * priceLabel;
@property (nonatomic, weak)UILabel * orPriceLabel;
@property (nonatomic, weak)UILabel * timeLabel;
@property (nonatomic, weak)UILabel * dateLabel;
//@property (nonatomic, strong)UILabel * countLabel;
//@property (nonatomic, strong)UIButton * subtractButton;
//@property (nonatomic, strong)UIButton * addButton;
@property (nonatomic, strong)UIButton * showDiscountButton;
@property (nonatomic, strong)UILabel * disLabel;
@property (nonatomic, weak)UILabel * discountPriceLabel;
@property (nonatomic, weak)UIImageView * rightImageView;
//@property (nonatomic, strong)UILabel * tuanLabel;
//@property (nonatomic, weak)UILabel * tuanPriceLabel;
@property (nonatomic, weak)UILabel * lightGrayLabel;
@property (nonatomic, strong)UILabel * smallTotalLabel;
@property (nonatomic, weak)UILabel * yellowLabel;
//@property (nonatomic, assign)int count;
@property (nonatomic, assign)int is_user_bill;
@property (nonatomic, assign)float totle;
@property (nonatomic, strong)NSIndexPath * indexPath;
@property (nonatomic, copy)NSString * user_coupons_id;

@property (nonatomic, strong)UILabel * balanceLabel;
@property (nonatomic, weak)UILabel * valueLabel;
@property (nonatomic, strong)UILabel * symbolLabel;
@property (nonatomic, strong)UILabel * payStyleLabel;
@property (nonatomic, strong)UIButton * zhifubaoButton;
@property (nonatomic, strong)UIButton * weixinButton;
@property (nonatomic, strong)UIView * middleView;
@property (nonatomic, weak)UIView * bottomView;
@property (nonatomic, strong)UILabel * discountLabel;
@property (nonatomic, strong)UILabel * totalLabel;
@property (nonatomic, weak)UIButton * sureButton;
@property (nonatomic, weak)UISwitch * billSwitch;

@property (nonatomic, strong)UIView * oneLineView;
@property (nonatomic, strong)UIView * twoLineView;
@property (nonatomic, strong)UIView * fourLineView;

@property (nonatomic, copy)NSString * payStyle;

@property (nonatomic, weak)UIToolbar *toolbar;
@property (nonatomic, weak)UIView * couponView;
@property (nonatomic, weak)UITableView * couponTableView;
@property (nonatomic, strong)NSArray<SureUserCouponModel *> *couponArray;

@property (nonatomic, weak)UILabel * showLabel;

@property (nonatomic, weak)UIToolbar * sureToolbar;
@property (nonatomic, weak)UIView * whiteView;
@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray * dataArray;
@property (nonatomic, copy)NSString * discout;
@property (nonatomic, copy)NSString * balance;
@property (nonatomic, copy)NSString * payMoneyCount;

@property (nonatomic, weak)UIImageView * localImageView;
@property (nonatomic, strong)UILabel * localLabel;

@end

@implementation SureOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //    self.count = 1;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zhifuNotification:) name:@"zhifuNotification" object:nil];
    
    self.is_user_bill = 0;
    self.balance = @"-￥0.00";
    self.dataArray = @[@"日期",@"时间",@"商品价格",@"折扣减",@"优惠券",@"余额抵扣"];
    [self loadData];
    [self setupNav];
    [self setupUI];
}

- (void)loadData{
    
    [[ZRNetworkTool sharedTool] getUserBillResultWithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            self.valueLabel.text = [NSString stringWithFormat:@"%@",responseData[@"data"]];
        }
    }];
    //    NSLog(@"self.dict===%@",self.dict);
    NSString * merchants_goods_merchants_id = [NSString stringWithFormat:@"%@",self.dict[@"merchants_goods_merchants_id"]];
    NSString * merchants_goods_category = [NSString stringWithFormat:@"%@",self.dict[@"merchants_goods_type"]];
    NSString * goods_category_id = [NSString stringWithFormat:@"%@",self.dict[@"merchants_goods_category"]];
    NSString * ID = [NSString stringWithFormat:@"%@",self.dict[@"id"]];
    //    NSLog(@"===%@",merchants_goods_merchants_id);
    
    //    [[ZRNetworkTool sharedTool] getUserCouponsResultWithMerchants_id:merchants_goods_merchants_id WithBlock:^(BOOL success, id responseData) {
    //
    //        if (success) {
    //
    //            self.couponArray = [NSArray yy_modelArrayWithClass:[SureUserCouponModel class] json:responseData[@"data"]];
    //        }
    //    }];
    
    
    //    [[ZRNetworkTool sharedTool] getUserCouponsResultWithMerchants_id:merchants_goods_merchants_id WithGoods_Category_ID:goods_category_id WithGoods_type:merchants_goods_category WithBlock:^(BOOL success, id responseData) {
    //
    //        if (success) {
    //
    //            self.couponArray = [NSArray yy_modelArrayWithClass:[SureUserCouponModel class] json:responseData[@"data"]];
    //        }
    //    }];
    
    [[ZRNetworkTool sharedTool] getUserCouponsResultWithMerchants_id:merchants_goods_merchants_id WithGoods_Category_ID:goods_category_id WithGoods_type:merchants_goods_category WithCoods_id:ID WithGoods_field:self.time WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            self.couponArray = [NSArray yy_modelArrayWithClass:[SureUserCouponModel class] json:responseData[@"data"]];
        }
        
    }];
}


- (void)setCouponArray:(NSArray<SureUserCouponModel *> *)couponArray{
    
    _couponArray = couponArray;
    
    [self.couponTableView reloadData];
}

- (void)setupNav{
    
    self.title = @"确认订单";
    
    //    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back(1)"] style:UIBarButtonItemStylePlain target:nil action:nil];
    //
    //    self.navigationItem.backBarButtonItem = backItem;
}


- (void)setupUI{
    
    self.payStyle = @"ZFB_APPAPI";
    self.view.backgroundColor = ColorWithRGB(0xF5F5F5);
    
    self.topView = [self setupView];
    [self.view addSubview:self.topView];
    self.middleView = [self setupView];
    [self.view addSubview:self.middleView];
    
    self.oneLineView = [self setupLineView];
    [self.topView addSubview:self.oneLineView];
    self.twoLineView = [self setupLineView];
    [self.topView addSubview:self.twoLineView];
    self.fourLineView = [self setupLineView];
    [self.middleView addSubview:self.fourLineView];
    
    NSArray * shopArray = [self.dict[@"merchants_img"] componentsSeparatedByString:@","];
    NSString * shopImg = shopArray.firstObject;
    NSString * shopStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,shopImg];
    NSURL * shopUrl = [NSURL URLWithString:shopStr];
    
    UIImageView * iconImageView = [UIImageView new];
    
    //    iconImageView.backgroundColor = [UIColor lightGrayColor];
    [iconImageView sd_setImageWithURL:shopUrl];
    iconImageView.layer.cornerRadius = 15 * SCREENH6;
    iconImageView.layer.masksToBounds = YES;
    
    self.iconImageView = iconImageView;
    
    [self.topView addSubview:self.iconImageView];
    
    
    UILabel * shopNameLabel = [UILabel new];
    
    shopNameLabel.textColor = [UIColor lightGrayColor];
    shopNameLabel.text = self.dict[@"merchants_name"];
    shopNameLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.shopNameLabel = shopNameLabel;
    
    [self.topView addSubview:self.shopNameLabel];
    
    
    NSArray * goodsArray = [self.dict[@"merchants_goods_img"] componentsSeparatedByString:@","];
    NSString * goodsImg = goodsArray.firstObject;
    NSString * goodsStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,goodsImg];
    NSURL * goodsUrl = [NSURL URLWithString:goodsStr];
    
    UIImageView * goodsImageView = [UIImageView new];
    
    //    goodsImageView.backgroundColor = [UIColor lightGrayColor];
    [goodsImageView sd_setImageWithURL:goodsUrl];
    
    self.goodsImageView = goodsImageView;
    
    [self.topView addSubview:self.goodsImageView];
    
    self.goodsNameLabel = [self setupLabelWithTitle:self.dict[@"merchants_goods_name"]];
    self.goodsNameLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    [self.topView addSubview:self.goodsNameLabel];
    
    UILabel * orPriceLabel = [UILabel new];
    
    NSString * orString = [NSString stringWithFormat:@"￥%@",self.dict[@"merchatns_goods_platform_price"]];
    //中划线
    NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:orString attributes:attribtDic];
    orPriceLabel.textColor = [UIColor lightGrayColor];
    orPriceLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    orPriceLabel.textAlignment = NSTextAlignmentRight;
    orPriceLabel.attributedText = attribtStr;
    
    self.orPriceLabel = orPriceLabel;
    
    [self.topView addSubview:self.orPriceLabel];
    
    NSString * priceStr = [NSString stringWithFormat:@"￥%@",self.dict[@"merchatns_goods_platform_discount_price"]];
    self.priceLabel = [self setupLabelWithTitle:priceStr];
    self.priceLabel.textAlignment = NSTextAlignmentRight;
    [self.topView addSubview:self.priceLabel];
    
    NSArray *array = [self.time componentsSeparatedByString:@" "];
    
    UILabel * dateLabel = [UILabel new];
    
    dateLabel.textColor = ZRBlackColor;
    dateLabel.text = [NSString stringWithFormat:@"日期:%@",array.firstObject];
    dateLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    
    self.dateLabel = dateLabel;
    
    [self.topView addSubview:self.dateLabel];
    
    UILabel * timeLabel = [UILabel new];
    
    timeLabel.textColor = ZRBlackColor;
    timeLabel.text = [NSString stringWithFormat:@"时间:%@",array.lastObject];
    timeLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    
    self.timeLabel = timeLabel;
    
    [self.topView addSubview:self.timeLabel];
    
    self.localLabel = [self setupLabelWithTitle:self.dict[@"merchants_address"]];
    self.localLabel.textColor = ColorWithRGB(0x4c87d8);
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(pushToMapView)];
    self.localLabel.userInteractionEnabled = YES;
    [self.localLabel addGestureRecognizer:tapGR];
    [self.topView addSubview:self.localLabel];
    
    UIImageView * localImageView = [UIImageView new];
    localImageView.image = [UIImage imageNamed:@"place(1)"];
    self.localImageView = localImageView;
    [self.topView addSubview:self.localImageView];
    
    //    self.countLabel = [self setupLabelWithTitle:@"1"];
    //    [self.topView addSubview:self.countLabel];
    //
    //    self.subtractButton = [self setupButtonWithTitle:@"substract"];
    //    [self.topView addSubview:self.subtractButton];
    //    self.addButton = [self setupButtonWithTitle:@"addcount"];
    //    [self.topView addSubview:self.addButton];
    
    UIButton * showButton = [UIButton new];
    
    [showButton addTarget:self action:@selector(cilckShowButton) forControlEvents:UIControlEventTouchUpInside];
    self.showDiscountButton = showButton;
    
    [self.topView addSubview:self.showDiscountButton];
    
    self.disLabel = [self setupLabelWithTitle:@"优惠券"];
    [self.showDiscountButton addSubview:self.disLabel];
    
    UILabel * discountPriceLabel = [UILabel new];
    
    discountPriceLabel.textColor = ColorWithRGB(0xFFE055);
    discountPriceLabel.text = @"选择优惠券";
    discountPriceLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.discountPriceLabel = discountPriceLabel;
    
    [self.showDiscountButton addSubview:self.discountPriceLabel];
    
    UIImageView * rightImageView = [UIImageView new];
    
    rightImageView.image = [UIImage imageNamed:@"右箭头"];
    
    self.rightImageView = rightImageView;
    
    [self.showDiscountButton addSubview:self.rightImageView];
    
    UILabel * grayLabel = [UILabel new];
    
    grayLabel.textColor = [UIColor lightGrayColor];
    float price = [self.dict[@"merchatns_goods_platform_discount_price"] floatValue];
    float orprice = [self.dict[@"merchatns_goods_platform_price"] floatValue];
    float res = orprice - price;
    grayLabel.text = [NSString stringWithFormat:@"已优惠￥%.2f",res];
    grayLabel.font = [UIFont systemFontOfSize:12 * SCREENH6];
    
    self.lightGrayLabel = grayLabel;
    
    [self.topView addSubview:self.lightGrayLabel];
    
    self.smallTotalLabel = [self setupLabelWithTitle:@"小计"];
    [self.topView addSubview:self.smallTotalLabel];
    
    UILabel * yellowLabel = [UILabel new];
    
    yellowLabel.textColor = ColorWithRGB(0xFFE055);
    yellowLabel.text = [NSString stringWithFormat:@"￥%@",self.dict[@"merchatns_goods_platform_discount_price"]];
    yellowLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    self.yellowLabel = yellowLabel;
    
    [self.topView addSubview:self.yellowLabel];
    
    self.balanceLabel = [self setupLabelWithTitle:@"余额支付(￥"];
    [self.middleView addSubview:self.balanceLabel];
    
    UILabel * valueLabel = [UILabel new];
    
    valueLabel.textColor = ColorWithRGB(0xFFE055);
    valueLabel.text = @"40";
    valueLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
    self.valueLabel = valueLabel;
    
    [self.middleView addSubview:self.valueLabel];
    
    self.symbolLabel = [self setupLabelWithTitle:@")"];
    [self.middleView addSubview:self.symbolLabel];
    
    UISwitch * billSwitch = [UISwitch new];
    
    [billSwitch setTintColor:ColorWithRGB(0xeeeeee)];
    [billSwitch setOnTintColor:ColorWithRGB(0xFFE055)];
    [billSwitch setThumbTintColor:ZRWhiteColor];
    billSwitch.backgroundColor = ColorWithRGB(0xeeeeee);
    billSwitch.layer.cornerRadius = 15.5 * SCREENH6;
    billSwitch.layer.masksToBounds = YES;
    [billSwitch addTarget:self action:@selector(switchAction) forControlEvents:UIControlEventValueChanged];
    self.billSwitch = billSwitch;
    
    [self.middleView addSubview:self.billSwitch];
    
    
    self.payStyleLabel = [self setupLabelWithTitle:@"支付方式"];
    [self.middleView addSubview:self.payStyleLabel];
    
    self.zhifubaoButton = [self setupPayStyleButtonWithTitle:@" 支付宝"];
    self.zhifubaoButton.selected = YES;
    [self.middleView addSubview:self.zhifubaoButton];
    self.weixinButton = [self setupPayStyleButtonWithTitle:@" 微信"];
    [self.middleView addSubview:self.weixinButton];
    
    UIView * bottomView = [UIView new];
    bottomView.backgroundColor = ZRBlackColor;
    self.bottomView = bottomView;
    [self.view addSubview:self.bottomView];
    
    self.discountLabel = [self setupWhiteLabelWithTitle:@"已优惠￥32" WithType:@"small"];
    self.discountLabel.text = self.lightGrayLabel.text;
    self.discountLabel.textAlignment = NSTextAlignmentCenter;
    [self.bottomView addSubview:self.discountLabel];
    self.totalLabel = [self setupWhiteLabelWithTitle:@"合计￥24" WithType:@"big"];
    self.totalLabel.text = [NSString stringWithFormat:@"￥%@",self.dict[@"merchatns_goods_platform_discount_price"]];
    self.totalLabel.textAlignment = NSTextAlignmentCenter;
    self.totle = [self.dict[@"merchatns_goods_platform_discount_price"] floatValue];
    [self.bottomView addSubview:self.totalLabel];
    
    UIButton * sureButton = [UIButton new];
    
    [sureButton setTitle:@"提交订单" forState:UIControlStateNormal];
    [sureButton setBackgroundColor:ColorWithRGB(0xFFE055)];
    [sureButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    sureButton.titleLabel.font = [UIFont systemFontOfSize:17 * SCREENH6];
    [sureButton addTarget:self action:@selector(clickSureButton) forControlEvents:UIControlEventTouchUpInside];
    
    self.sureButton = sureButton;
    
    [self.view addSubview:self.sureButton];
}


- (void)viewDidLayoutSubviews{
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(kNavHeight + kStatusBarHeight +10 * SCREENH6);
        make.height.mas_equalTo(260 * SCREENH6);
    }];
    
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.topView).offset(10 * SCREENH6);
        make.top.mas_equalTo(self.topView).offset(15 * SCREENH6);
        make.height.width.mas_equalTo(30 * SCREENH6);
    }];
    
    [self.shopNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.iconImageView.mas_trailing).offset(5 * SCREENH6);
        make.centerY.mas_equalTo(self.iconImageView);
    }];
    
    [self.oneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.iconImageView);
        make.trailing.mas_equalTo(self.topView).offset(-10 * SCREENH6);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(54 * SCREENH6);
    }];
    
    [self.goodsImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(85 * SCREENH6);
        make.top.mas_equalTo(self.oneLineView.mas_bottom).offset(10 * SCREENH6);
        make.leading.mas_equalTo(self.oneLineView);
    }];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.oneLineView);
        make.top.mas_equalTo(self.oneLineView.mas_bottom).offset(13 * SCREENH6);
    }];
    
    [self.orPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.priceLabel);
        make.top.mas_equalTo(self.priceLabel.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.goodsNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.priceLabel);
        make.leading.mas_equalTo(self.goodsImageView.mas_trailing).offset(5 * SCREENH6);
        make.trailing.mas_equalTo(self.orPriceLabel.mas_leading).offset(-5 * SCREENH6);
    }];
    
    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.goodsNameLabel);
        make.top.mas_equalTo(self.goodsNameLabel.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.dateLabel);
        make.top.mas_equalTo(self.dateLabel.mas_bottom).offset(5 * SCREENH6);
    }];
    
    //    [self.subtractButton mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.leading.mas_equalTo(self.timeLabel);
    //        make.top.mas_equalTo(self.timeLabel.mas_bottom).offset(5 * SCREENH6);
    //        make.height.width.mas_equalTo(22 * SCREENH6);
    //    }];
    //
    //    [self.countLabel mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerY.mas_equalTo(self.subtractButton);
    //        make.leading.mas_equalTo(self.subtractButton.mas_trailing).offset(5 * SCREENH6);
    //    }];
    //
    //    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerY.height.width.mas_equalTo(self.subtractButton);
    //        make.leading.mas_equalTo(self.countLabel.mas_trailing).offset(5 * SCREENH6);
    //    }];
    
    [self.localImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.goodsImageView);
        make.top.mas_equalTo(self.goodsImageView.mas_bottom).offset(10 * SCREENH6);
        make.width.mas_equalTo(13 * SCREENH6);
        make.height.mas_equalTo(16 * SCREENH6);
    }];
    
    [self.localLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.localImageView.mas_trailing).offset(5 * SCREENH6);
        make.trailing.mas_equalTo(self.oneLineView);
        make.centerY.mas_equalTo(self.localImageView);
    }];
    
    [self.showDiscountButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.oneLineView);
        make.top.mas_equalTo(self.localImageView.mas_bottom);
        make.height.mas_equalTo(40 * SCREENH6);
    }];
    
    [self.disLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.showDiscountButton);
        make.top.mas_equalTo(self.localImageView.mas_bottom).offset(15 * SCREENH6);
    }];
    
    [self.rightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.oneLineView);
        make.centerY.mas_equalTo(self.disLabel);
        make.width.mas_equalTo(7 * SCREENH6);
        make.height.mas_equalTo(12.5 * SCREENH6);
    }];
    
    [self.discountPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.rightImageView.mas_leading).offset(-5 * SCREENH6);
        make.centerY.mas_equalTo(self.rightImageView);
    }];
    
    [self.twoLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.oneLineView);
        make.top.mas_equalTo(self.rightImageView.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [self.yellowLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.rightImageView);
        make.top.mas_equalTo(self.twoLineView.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [self.smallTotalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.yellowLabel);
        make.trailing.mas_equalTo(self.yellowLabel.mas_leading).offset(-2 * SCREENH6);
    }];
    
    [self.lightGrayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.smallTotalLabel);
        make.trailing.mas_equalTo(self.smallTotalLabel.mas_leading).offset(-2 * SCREENH6);
    }];
    
    [self.middleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.topView);
        make.top.mas_equalTo(self.topView.mas_bottom).offset(15 * SCREENH6);
        make.height.mas_equalTo(90 * SCREENH6);
    }];
    
    [self.fourLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.middleView);
        make.height.leading.trailing.mas_equalTo(self.twoLineView);
    }];
    
    [self.balanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.disLabel);
        make.top.mas_equalTo(self.middleView).offset(15 * SCREENH6);
    }];
    
    [self.valueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.balanceLabel);
        make.leading.mas_equalTo(self.balanceLabel.mas_trailing);
    }];
    
    [self.symbolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.valueLabel);
        make.leading.mas_equalTo(self.valueLabel.mas_trailing);
    }];
    
    [self.billSwitch mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.rightImageView);
        make.centerY.mas_equalTo(self.symbolLabel);
        //        make.width.mas_equalTo(40 * SCREENH6);
        //        make.height.mas_equalTo(25 * SCREENH6);
    }];
    
    [self.payStyleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.balanceLabel);
        make.top.mas_equalTo(self.fourLineView.mas_bottom).offset(12 * SCREENH6);
    }];
    
    [self.zhifubaoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.payStyleLabel.mas_trailing).offset(20 * SCREENH6);
        make.centerY.mas_equalTo(self.payStyleLabel);
        make.width.mas_equalTo(80 * SCREENH6);
        make.height.mas_equalTo(20 * SCREENH6);
    }];
    
    [self.weixinButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.width.height.mas_equalTo(self.zhifubaoButton);
        make.leading.mas_equalTo(self.zhifubaoButton.mas_trailing).offset(20 * SCREENH6);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-kBarHeight);
        make.height.mas_equalTo(60 * SCREENH6);
        make.width.mas_equalTo(250 * SCREENH6);
    }];
    
    [self.discountLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bottomView).offset(5 * SCREENH6);
        make.centerX.mas_equalTo(self.bottomView);
    }];
    
    [self.totalLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.discountLabel.mas_bottom).offset(5 * SCREENH6);
        make.centerX.mas_equalTo(self.discountLabel);
    }];
    
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view).offset(-kBarHeight);
        make.leading.mas_equalTo(self.bottomView.mas_trailing);
        make.height.mas_equalTo(self.bottomView);
    }];
}

- (UIButton *)setupPayStyleButtonWithTitle:(NSString *)title{
    
    UIButton * button = [UIButton new];
    
    [button setTitle:title forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"椭圆1"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"选中椭圆"] forState:UIControlStateSelected];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [button setTitleColor:ColorWithRGB(0xFFE055) forState:UIControlStateSelected];
    button.titleLabel.font = [UIFont systemFontOfSize:13.5 * SCREENH6];
    [button addTarget:self action:@selector(clickPayStyleButton:) forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

- (UILabel *)setupLabelWithTitle:(NSString *)title{
    
    UILabel * label = [UILabel new];
    
    label.textColor = ZRBlackColor;
    label.text = title;
    label.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
    return label;
}

- (UIView *)setupView{
    
    UIView * view = [UIView new];
    
    view.backgroundColor = ZRWhiteColor;
    view.layer.cornerRadius = 5;
    view.layer.masksToBounds = YES;
    view.userInteractionEnabled = YES;
    
    return view;
}

- (UILabel *)setupWhiteLabelWithTitle:(NSString *)title WithType:(NSString *)type{
    
    UILabel * label = [UILabel new];
    
    label.text = title;
    label.textColor = ZRWhiteColor;
    if ([type isEqualToString:@"small"]) {
        
        label.font = [UIFont systemFontOfSize:14 * SCREENH6];
    }else{
        
        label.font = [UIFont systemFontOfSize:18 * SCREENH6];
    }
    
    return label;
}


- (UIView *)setupLineView{
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xF5F5F5);
    
    return lineView;
}


//- (UIButton *)setupButtonWithTitle:(NSString *)title{
//
//    UIButton * button = [UIButton new];
//
//    [button setImage:[UIImage imageNamed:title] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(clickSubtractOrAddButton:) forControlEvents:UIControlEventTouchUpInside];
//
//    return button;
//}

- (void)clickPayStyleButton:(UIButton *)button{
    
    if (button == self.zhifubaoButton) {
        
        if (!button.selected) {
            
            self.payStyle = @"ZFB_APPAPI";
            button.selected = YES;
            self.weixinButton.selected = NO;
        }
    }else if (button == self.weixinButton){
        
        if (!button.selected) {
            
            self.payStyle = @"WX_APPAPI";
            button.selected = YES;
            self.zhifubaoButton.selected = NO;
        }
    }
    
}

- (void)cilckShowButton{
    
    [self setupCouponView];
}

//- (void)clickSubtractOrAddButton:(UIButton *)button{
//
//    if (button == self.addButton) {
//
//        //        int count = [self.countLabel.text intValue];
//
//        self.count = self.count + 1;
//    }else{
//
//        //        int count = [self.countLabel.text intValue];
//
//        if (self.count == 1) {
//
//            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
//                                                                           message:@"亲，不能再少了！"
//                                                                    preferredStyle:UIAlertControllerStyleAlert];
//
//            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
//                                                                  handler:^(UIAlertAction * action) {
//
//                                                                  }];
//
//            [alert addAction:defaultAction];
//            [self presentViewController:alert animated:YES completion:nil];
//
//        }else{
//
//            self.count = self.count - 1;
//            //            self.countLabel.text = [NSString stringWithFormat:@"%d",count];
//        }
//    }
//}

- (void)clickSureButton{
    
    //    //获取当前时间日期
    //    NSDate *date=[NSDate date];
    //    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    //    [format1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //    NSString *dateStr;
    //    dateStr=[format1 stringFromDate:date];
    //
    //    NSString * is_user_bill = [NSString stringWithFormat:@"%d",self.is_user_bill];
    ////    NSString * buy_number = [NSString stringWithFormat:@"%d",self.count];
    //    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    //
    //    if (self.user_coupons_id) {
    //
    //        [dict setObject:dateStr forKey:@"timeStamp"];
    //        [dict setObject:self.orderID forKey:@"id"];
    //        [dict setObject:is_user_bill forKey:@"is_user_bill"];
    //        [dict setObject:@"1" forKey:@"buy_number"];
    //        [dict setObject:self.user_coupons_id forKey:@"user_coupons_id"];
    //    }else{
    //
    //        [dict setObject:dateStr forKey:@"timeStamp"];
    //        [dict setObject:self.orderID forKey:@"id"];
    //        [dict setObject:is_user_bill forKey:@"is_user_bill"];
    //        [dict setObject:@"1" forKey:@"buy_number"];
    //    }
    //
    //    NSString * sign = [self signStr:dict.copy];
    //
    //    [dict setObject:sign forKey:@"sign"];
    //
    //    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
    //                                                                   message:@"确认支付"
    //                                                            preferredStyle:UIAlertControllerStyleAlert];
    //
    //    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
    //                                                          handler:^(UIAlertAction * action) {
    //
    //                                                              [[NetworkTool sharedTools] POST:@"Api/sureSubmitGoodsOrder" parameters:dict.copy progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
    //
    //                                                                  int code = [responseObject[@"code"] intValue];
    //
    //                                                                  if (code == 200) {
    //                                                                      NSDictionary * dict = responseObject[@"data"];
    //                                                                      int need_pay = [dict[@"need_pay"] intValue];
    //
    //                                                                      if (need_pay == 1) {
    //
    //                                                                          [self payMoney];
    //                                                                      }else{
    //
    //                                                                          [self showSuccessPushOrder];
    //                                                                      }
    //
    //                                                                  }else{
    //
    //                                                                      UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
    //                                                                                                                                     message:responseObject[@"message"]
    //                                                                                                                              preferredStyle:UIAlertControllerStyleAlert];
    //
    //                                                                      UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
    //                                                                                                                            handler:^(UIAlertAction * action) {
    //
    //                                                                                                                            }];
    //
    //                                                                      [alert addAction:defaultAction];
    //                                                                      [self presentViewController:alert animated:YES completion:nil];
    //                                                                  }
    //
    //                                                              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //
    //                                                              }];
    //                                                          }];
    //    UIAlertAction* cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
    //                                                         handler:^(UIAlertAction * action) {
    //
    //                                                             //                                                                             [self cancleOrder];
    //                                                         }];
    //
    //    [alert addAction:defaultAction];
    //    [alert addAction:cancleAction];
    //    [self presentViewController:alert animated:YES completion:nil];
    
    [self setupSureToolView];
}

- (void)cancleOrder{
    
    
}


- (void)payMoney{
    
    if ([self.payStyle isEqualToString:@"WX_APPAPI"]) {
        
        NSString * user_id = DEF_GET_OBJECT(@"id");
        NSString * IP = [self getIPAddress];
        NSDictionary * dict = @{@"user_id":user_id,@"goods_order_id":self.orderID,@"pay_type":@"WX_APPAPI",@"spbill_create_ip":IP};
        
        [[NetworkTool sharedTools] POST:@"WxjsAPI/payApiCall" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            int code = [responseObject[@"code"] intValue];
            
            if (code == 200) {
                NSDictionary * data = responseObject[@"data"];
                [WXApiManager sharedManager].delegate = self;
                [[WXApiManager sharedManager] weiXinPayWithDic:data];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }else if([self.payStyle isEqualToString:@"ZFB_APPAPI"]){
        
        NSString * user_id = DEF_GET_OBJECT(@"id");
        NSDictionary * dict = @{@"user_id":user_id,@"goods_order_id":self.orderID,@"pay_type":@"ZFB_APPAPI"};
        
        [[NetworkTool sharedTools] POST:@"WxjsAPI/payApiCall" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            int code = [responseObject[@"code"] intValue];
            
            if (code == 200) {
                
                NSString * data = [NSString stringWithFormat:@"%@",responseObject[@"data"]];
                NSString *appScheme = @"FindifZhifubao20181105";
                
                [[AlipaySDK defaultService] payOrder:data fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    
                    
                }];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
        
    }
}


- (void)didLeftNavButton{
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (NSString *)signStr:(NSDictionary *)dict{
    
    NSArray *keyArray = [dict allKeys];
    
    //定义一个排序数组，存储排序好之后的key值
    NSArray *sortArray = [keyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    
    //这时我们再创建一个数组，来按升序存储key对应的Value，通过遍历sortArray的方法
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortString in sortArray) {
        [valueArray addObject:[dict objectForKey:sortString]];
    }
    //    现在我们有两个数组，分别对应升序排序的key和value，所以再创建一个keyValue的数组来存储每一个key和value的格式
    //    NSMutableArray *signArray = [NSMutableArray array];
    //    for (int i = 0; i < sortArray.count; i++) {
    //        NSString *keyValueStr = [NSString stringWithFormat:@"%@:%@",sortArray[i],valueArray[i]];
    //        [signArray addObject:keyValueStr];
    //    }
    
    //最后的一步，就是用“,”把每个字符串拼接起来
    NSString *sign = [valueArray componentsJoinedByString:@""];
    
    NSString * resStr = [NSString stringWithFormat:@"%@NDQ0NTlmMDk4MTU3NTg3NzFiZTFlZmQwNDFjNzA0ZGMyYWY0NzU5ZQ==",sign];
    
    NSString *signStr = [self md5:resStr];
    
    NSString * baseStr = [self encode:signStr];
    
    return baseStr;
}

- (NSString *) md5:(NSString *) str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

- (NSString *)encode:(NSString *)string
{
    //先将string转换成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    
    return baseString;
}


// 获取设备IP地址
-(NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // 检索当前接口,在成功时,返回0
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // 循环链表的接口
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // 检查接口是否en0 wifi连接在iPhone上
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // 得到NSString从C字符串
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // 释放内存
    freeifaddrs(interfaces);
    return address;
}


- (void)switchAction{
    //判断开关的状态
    if (self.billSwitch.on) {
        //        NSLog(@"switch is on");
        self.is_user_bill = 1;
        
        float value = [self.valueLabel.text floatValue];
        float res = value - self.totle;
        if (res >= 0) {
            
            self.totalLabel.text = [NSString stringWithFormat:@"合计￥0.00"];
            
        }else{
            //            float ;
            self.totalLabel.text = [NSString stringWithFormat:@"合计￥%.2f",fabsf(res)];
        }
        
        if (value >= self.totle) {
            
            self.balance = [NSString stringWithFormat:@"-￥%.2f",self.totle];
        }else{
            
            self.balance = [NSString stringWithFormat:@"-￥%.2f",value];
        }
        
    } else {
        //        NSLog(@"switch is off");
        self.is_user_bill = 0;
        self.balance = @"-￥0.00";
        self.totalLabel.text = [NSString stringWithFormat:@"合计￥%.2f",self.totle];
    }
}


- (void)setupSureToolView{
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
    //透明度
    toolbar.alpha = 0.5f;
    toolbar.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeSureToolView)];
    [toolbar addGestureRecognizer:tapGR];
    
    self.sureToolbar = toolbar;
    [self.tabBarController.view addSubview:self.sureToolbar];
    
    UIView * whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH - 355 * SCREENH6, kScreenW, 355 * SCREENH6)];
    
    whiteView.backgroundColor = ZRWhiteColor;
    whiteView.userInteractionEnabled = YES;
    
    self.whiteView = whiteView;
    
    [self.tabBarController.view addSubview:self.whiteView];
    
    
    UIButton * closeButton = [UIButton new];
    
    [closeButton setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(removeSureToolView) forControlEvents:UIControlEventTouchUpInside];
    
    [self.whiteView addSubview:closeButton];
    
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.text = self.dict[@"merchants_goods_name"];
    titleLabel.textColor = ZRBlackColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.whiteView addSubview:titleLabel];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    [self.whiteView addSubview:lineView];
    
    UILabel * moneyLabel = [UILabel new];
    
    moneyLabel.text = [NSString stringWithFormat:@"%@",self.totalLabel.text];
    moneyLabel.textColor = ZRBlackColor;
    moneyLabel.font = [UIFont boldSystemFontOfSize:20 * SCREENH6];
    
    [self.whiteView addSubview:moneyLabel];
    
    UILabel * exploreLabel = [UILabel new];
    
    exploreLabel.text = [NSString stringWithFormat:@"如需取消，请在开场前%@小时取消订单",self.dict[@"merchants_goods_cancel_order_time"]];
    exploreLabel.textColor = [UIColor redColor];
    exploreLabel.font = [UIFont boldSystemFontOfSize:13 * SCREENH6];
    exploreLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.whiteView addSubview:exploreLabel];
    
    UIButton * payButton = [UIButton new];
    
    NSString * money = [NSString stringWithFormat:@"确认支付%@元",self.totalLabel.text];
    [payButton setTitle:money forState:UIControlStateNormal];
    [payButton setTitleColor:ZRWhiteColor forState:UIControlStateNormal];
    [payButton addTarget:self action:@selector(clickPayButton) forControlEvents:UIControlEventTouchUpInside];
    [payButton setBackgroundColor:ZRBlackColor];
    payButton.layer.cornerRadius = 5 * SCREENH6;
    payButton.layer.masksToBounds = YES;
    payButton.titleLabel.font = [UIFont systemFontOfSize:16 * SCREENH6];
    
    [self.whiteView addSubview:payButton];
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 48 * SCREENH6, kScreenW, 180 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.rowHeight = 30 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.scrollEnabled = NO;
    
    self.tableView = tableView;
    
    [self.whiteView addSubview:self.tableView];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView);
        make.width.mas_equalTo(210 * SCREENH6);
        make.top.mas_equalTo(self.whiteView).offset(12 * SCREENH6);
    }];
    
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.whiteView).offset(15 * SCREENH6);
        make.centerY.mas_equalTo(titleLabel);
        make.width.height.mas_equalTo(20 * SCREENH6);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.whiteView);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(self.whiteView).offset(40 * SCREENH6);
    }];
    
    [moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView);
        make.top.mas_equalTo(self.tableView.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [payButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView);
        make.top.mas_equalTo(moneyLabel.mas_bottom).offset(17 * SCREENH6);
        make.width.mas_equalTo(200 * SCREENH6);
        make.height.mas_equalTo(30 * SCREENH6);
    }];
    
    [exploreLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.whiteView);
        make.top.mas_equalTo(payButton.mas_bottom).offset(10 * SCREENH6);
    }];
}


- (void)removeSureToolView{
    
    [self.sureToolbar removeFromSuperview];
    [self.whiteView removeFromSuperview];
}


- (void)clickPayButton{
    
    //获取当前时间日期
    NSDate *date=[NSDate date];
    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr;
    dateStr=[format1 stringFromDate:date];
    
    NSString * is_user_bill = [NSString stringWithFormat:@"%d",self.is_user_bill];
    //    NSString * buy_number = [NSString stringWithFormat:@"%d",self.count];
    NSMutableDictionary * dict = [NSMutableDictionary dictionary];
    
    if (self.user_coupons_id) {
        
        [dict setObject:dateStr forKey:@"timeStamp"];
        [dict setObject:self.orderID forKey:@"id"];
        [dict setObject:is_user_bill forKey:@"is_user_bill"];
        [dict setObject:@"1" forKey:@"buy_number"];
        [dict setObject:self.user_coupons_id forKey:@"user_coupons_id"];
    }else{
        
        [dict setObject:dateStr forKey:@"timeStamp"];
        [dict setObject:self.orderID forKey:@"id"];
        [dict setObject:is_user_bill forKey:@"is_user_bill"];
        [dict setObject:@"1" forKey:@"buy_number"];
    }
    
    NSString * sign = [self signStr:dict.copy];
    
    [dict setObject:sign forKey:@"sign"];
    
    [[NetworkTool sharedTools] POST:@"Api/sureSubmitGoodsOrder" parameters:dict.copy progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary *  _Nullable responseObject) {
        
        int code = [responseObject[@"code"] intValue];
        
        if (code == 200) {
            NSDictionary * dict = responseObject[@"data"];
            int need_pay = [dict[@"need_pay"] intValue];
            
            if (need_pay == 1) {
                
                [self payMoney];
            }else{
                
                [self showSuccessPushOrder];
            }
            
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseObject[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
    
    [self.sureToolbar removeFromSuperview];
    [self.whiteView removeFromSuperview];
}


- (void)setupCouponView{
    
    UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //样式
    toolbar.barStyle = UIBarStyleBlackTranslucent;//半透明
    //透明度
    toolbar.alpha = 0.5f;
    toolbar.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [toolbar addGestureRecognizer:tapGR];
    
    self.toolbar = toolbar;
    [self.tabBarController.view addSubview:self.toolbar];
    
    UIView * couponView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenH - 300 * SCREENH6, kScreenW, 300 * SCREENH6)];
    
    couponView.backgroundColor = ZRWhiteColor;
    couponView.userInteractionEnabled = YES;
    
    self.couponView = couponView;
    
    [self.tabBarController.view addSubview:self.couponView];
    
    
    UIButton * noCouponButton = [UIButton new];
    
    //    [noCouponButton setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [noCouponButton setTitle:@"暂不使用" forState:UIControlStateNormal];
    [noCouponButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    [noCouponButton addTarget:self action:@selector(clickNoCouponButton) forControlEvents:UIControlEventTouchUpInside];
    noCouponButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    
    [self.couponView addSubview:noCouponButton];
    
    
    UIButton * closeButton = [UIButton new];
    
    [closeButton setImage:[UIImage imageNamed:@"关闭"] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(clickCloseButton) forControlEvents:UIControlEventTouchUpInside];
    
    [self.couponView addSubview:closeButton];
    
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.text = @"优惠详情";
    titleLabel.textColor = ZRBlackColor;
    titleLabel.font = [UIFont boldSystemFontOfSize:15 * SCREENH6];
    
    [self.couponView addSubview:titleLabel];
    
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xe4e4e4);
    
    [self.couponView addSubview:lineView];
    
    UILabel * showLabel = [UILabel new];
    
    showLabel.text = @"暂无优惠券";
    showLabel.textColor = ZRBlackColor;
    showLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    showLabel.hidden = YES;
    
    self.showLabel = showLabel;
    
    [self.couponView addSubview:self.showLabel];
    
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40 * SCREENH6, kScreenW, 270 * SCREENH6) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor clearColor];
    tableView.rowHeight = 105 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.couponTableView = tableView;
    
    [self.couponTableView registerClass:[NewCouponTableViewCell class] forCellReuseIdentifier:@"UserCouponTableViewCell"];
    
    [self.couponView addSubview:self.couponTableView];
    
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.couponView);
        make.top.mas_equalTo(self.couponView).offset(10 * SCREENH6);
    }];
    
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.couponView).offset(-10 * SCREENH6);
        make.centerY.mas_equalTo(titleLabel);
        make.width.height.mas_equalTo(15 * SCREENH6);
    }];
    
    [noCouponButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.couponView).offset(10 * SCREENH6);
        make.centerY.mas_equalTo(titleLabel);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.couponView);
        make.height.mas_equalTo(1 * SCREENH6);
        make.top.mas_equalTo(self.couponView).offset(40 * SCREENH6);
    }];
    
    [self.showLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.couponTableView);
        make.centerY.mas_equalTo(self.couponTableView);
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (self.couponArray.count == 0) {
        
        self.showLabel.hidden = NO;
    }else{
        
        self.showLabel.hidden = YES;
    }
    if (tableView == self.tableView) {
        
        return 6;
    }else{
        
        return self.couponArray.count;
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        
        static NSString * cellID=@"cellID";
        UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell==nil) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
        }
        cell.textLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
        cell.textLabel.text = self.dataArray[indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //        cell.detailTextLabel.text = self.dataArr[indexPath.row][@"Others1"];
        NSArray *array = [self.time componentsSeparatedByString:@" "];
        //        NSLog(@"self.time===%@",self.time);
        //        NSLog(@"array===%@",array);
        if (indexPath.row == 0) {
            
            cell.detailTextLabel.textColor = ZRBlackColor;
            cell.detailTextLabel.text = array[1];
        }else if (indexPath.row == 1){
            
            cell.detailTextLabel.textColor = ZRBlackColor;
            cell.detailTextLabel.text = array.lastObject;
        }else if (indexPath.row == 2){
            
            cell.detailTextLabel.textColor = ZRBlackColor;
            cell.detailTextLabel.text = [NSString stringWithFormat:@"￥%@",self.dict[@"merchatns_goods_platform_price"]];
        }else if (indexPath.row == 3){
            
            cell.detailTextLabel.textColor = ColorWithRGB(0xFFE055);
            NSString * orPriceStr = [NSString stringWithFormat:@"%@",self.dict[@"merchatns_goods_platform_price"]];
            NSString * priceStr = [NSString stringWithFormat:@"%@",self.dict[@"merchatns_goods_platform_discount_price"]];
            float orPrice = [orPriceStr floatValue];
            float price = [priceStr floatValue];
            NSString * resPrice = [NSString stringWithFormat:@"-￥%.2f",orPrice - price];
            cell.detailTextLabel.text = resPrice;
        }else if (indexPath.row == 4){
            
            cell.detailTextLabel.textColor = ColorWithRGB(0xFFE055);
            if (self.discout) {
                
                cell.detailTextLabel.text = [NSString stringWithFormat:@"-￥%@",self.discout];
            }else{
                
                cell.detailTextLabel.text = @"-￥0.00";
            }
        }else if (indexPath.row == 5){
            
            cell.detailTextLabel.textColor = ColorWithRGB(0xFFE055);
            cell.detailTextLabel.text = self.balance;
        }
        
        cell.backgroundColor = ZRWhiteColor;
        
        return cell;
    }else{
        
        NewCouponTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UserCouponTableViewCell" forIndexPath:indexPath];
        
        cell.userModel = self.couponArray[indexPath.row];
        //    cell.type = @"user";
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SureUserCouponModel * model = self.couponArray[indexPath.row];
    self.indexPath = indexPath;
    self.user_coupons_id = [NSString stringWithFormat:@"%@",model.id];
    float merchants_coupons_use_standard = [model.merchants_coupons_use_standard floatValue];
    float price = [self.dict[@"merchatns_goods_platform_discount_price"] floatValue];
    float orprice = [self.dict[@"merchatns_goods_platform_price"] floatValue];
    
    if (merchants_coupons_use_standard <= price) {
        int type = [model.merchants_coupons_type intValue];
        //代金券类型(1为满减 2为折扣)
        if(type == 1){
            
            self.discout = [NSString stringWithFormat:@"%@",model.merchants_coupons_discount];
            self.discountPriceLabel.text = [NSString stringWithFormat:@"-￥%@",model.merchants_coupons_discount];
            float price = [self.dict[@"merchatns_goods_platform_discount_price"] floatValue];
            float nowPrice = orprice - price;
            float discount = [model.merchants_coupons_discount floatValue];
            float res = nowPrice + discount;
            float paymoney = price - discount;
            if (paymoney < 0) {
                paymoney = 0;
            }
            self.lightGrayLabel.text = [NSString stringWithFormat:@"已优惠￥%.2f",res];
            self.discountLabel.text = self.lightGrayLabel.text;
            self.totalLabel.text = [NSString stringWithFormat:@"合计￥%.2f",paymoney];
            self.yellowLabel.text = [NSString stringWithFormat:@"￥%.2f",paymoney];
            self.totle = paymoney;
        }else{
            
            float merchants_coupons_discount = [model.merchants_coupons_discount floatValue];
            float nowPrice = orprice - price;
            float res = price * merchants_coupons_discount / 10;
            self.discout = [NSString stringWithFormat:@"%.2f",res];
            self.yellowLabel.text = [NSString stringWithFormat:@"￥%.2f",res];
            float show = price - res;
            if (res < 0) {
                res = 0;
            }
            self.discountPriceLabel.text = [NSString stringWithFormat:@"-￥%.2f",show];
            float lightGrayLabel = nowPrice + show;
            self.lightGrayLabel.text = [NSString stringWithFormat:@"已优惠￥%.2f",lightGrayLabel];
            self.discountLabel.text = self.lightGrayLabel.text;
            self.totalLabel.text = [NSString stringWithFormat:@"合计￥%.2f",res];
            self.totle = res;
        }
        
        [self.toolbar removeFromSuperview];
        [self.couponView removeFromSuperview];
        [self.couponTableView removeFromSuperview];
        
    }else{
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"亲，不好意思，您不满足优惠券的使用条件。"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                              }];
        
        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    
}

- (void)clickCloseButton{
    
    [self.toolbar removeFromSuperview];
    [self.couponView removeFromSuperview];
    [self.couponTableView removeFromSuperview];
}


- (void)clickNoCouponButton{
    
    self.discountPriceLabel.text = @"请选择优惠券";
    float price = [self.dict[@"merchatns_goods_platform_discount_price"] floatValue];
    float orPrice = [self.dict[@"merchatns_goods_platform_price"] floatValue];
    float discount = orPrice - price;
    
    self.lightGrayLabel.text = [NSString stringWithFormat:@"已优惠￥%.2f",discount];
    self.discountLabel.text = self.lightGrayLabel.text;
    self.totalLabel.text = [NSString stringWithFormat:@"合计￥%.2f",price];
    self.yellowLabel.text = [NSString stringWithFormat:@"￥%.2f",price];
    self.totle = price;
    
    [self.toolbar removeFromSuperview];
    [self.couponView removeFromSuperview];
    [self.couponTableView removeFromSuperview];
}

- (void)tapAction{
    
    [self.toolbar removeFromSuperview];
    [self.couponView removeFromSuperview];
    [self.couponTableView removeFromSuperview];
}

//- (void)setCount:(int)count{
//
//    _count = count;
//
//    self.countLabel.text = [NSString stringWithFormat:@"%d",count];
//    float price = [self.dict[@"merchants_goods_discount_price"] floatValue];
//    float orprice = [self.dict[@"merchants_goods_price"] floatValue];
//
//    float resOrPri = count * orprice;
//    float resPri = count * price;
//
//    self.orPriceLabel.text = [NSString stringWithFormat:@"￥%.2f",resOrPri];
//    self.priceLabel.text = [NSString stringWithFormat:@"￥%.2f",resPri];
//
//    if ([self.discountPriceLabel.text isEqualToString:@"选择优惠券"]) {
//
//        self.lightGrayLabel.text = [NSString stringWithFormat:@"已优惠￥%.2f",resOrPri - resPri];
//        self.discountLabel.text = self.lightGrayLabel.text;
//        self.yellowLabel.text = [NSString stringWithFormat:@"￥%.2f",resPri];
//        self.totalLabel.text = [NSString stringWithFormat:@"合计￥%.2f",resPri];
//        self.totle = resPri;
//    }else{
//        SureUserCouponModel * model = self.couponArray[self.indexPath.row];
//
//        int type = [model.merchants_coupons_type intValue];
//        //代金券类型(1为满减 2为折扣)
//        if(type == 1){
//
//            self.discountPriceLabel.text = [NSString stringWithFormat:@"-￥%@",model.merchants_coupons_discount];
//
//            float nowPrice = resOrPri - resPri;
//            float discount = [model.merchants_coupons_discount floatValue];
//            float res = nowPrice + discount;
//            float paymoney = resPri - discount;
//            self.lightGrayLabel.text = [NSString stringWithFormat:@"已优惠￥%.2f",res];
//            self.discountLabel.text = self.lightGrayLabel.text;
//            self.totalLabel.text = [NSString stringWithFormat:@"合计￥%.2f",paymoney];
//            self.yellowLabel.text = [NSString stringWithFormat:@"￥%.2f",paymoney];
//            self.totle = res;
//        }else{
//
//            float merchants_coupons_discount = [model.merchants_coupons_discount floatValue];
//            float nowPrice = resOrPri - resPri;
//            float res = resPri * merchants_coupons_discount / 10;
//            self.yellowLabel.text = [NSString stringWithFormat:@"￥%.2f",res];
//            float show = resPri - res;
//
//            self.discountPriceLabel.text = [NSString stringWithFormat:@"-￥%.2f",show];
//            float lightGrayLabel = nowPrice + show;
//            self.lightGrayLabel.text = [NSString stringWithFormat:@"已优惠￥%.2f",lightGrayLabel];
//            self.discountLabel.text = self.lightGrayLabel.text;
//            self.totalLabel.text = [NSString stringWithFormat:@"合计￥%.2f",res];
//            self.totle = res;
//        }
//    }
//}


- (void)managerDidRecvPaymentResponse:(PayResp *)response{
    
    //支付返回结果，实际支付结果需要去微信服务器端查询
    //    NSString *strMsg,*strTitle = [NSString stringWithFormat:@"支付结果"];
    
    switch (response.errCode) {
        case WXSuccess:
            
            [self showSuccessPushOrder];
            break;
        case -2:
            //用户取消
            [self pushToOrderVC];
            break;
        default:
            
            [self showErrorWithString:response.errStr];
            break;
    }
    
}

- (void)pushToOrderVC{
    
    if ([self.type isEqualToString:@"1"]) {
        
        for (UIViewController *controller in self.navigationController.viewControllers) {
            if ([controller isKindOfClass:[GroupActiveViewController class]]) {
                
                GroupActiveViewController *A =(GroupActiveViewController *)controller;
                [self.navigationController popToViewController:A animated:YES];
            }
        }
    }else{
        
        HiddenBar;
        MyOrderViewController * orderVC = [MyOrderViewController new];
        [self.navigationController pushViewController:orderVC animated:YES];
    }
    
}

- (void)showSuccessPushOrder{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"支付成功，快去使用吧！"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                              [self pushToOrderVC];
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)showErrorWithString:(NSString *)string{
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:string
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                          }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)zhifuNotification:(NSNotification *)noti{
    
    NSString * memo = noti.userInfo[@"memo"];
    
    if ([noti.userInfo[@"resultStatus"] isEqualToString:@"9000"]) {
        
        [self showSuccessPushOrder];
    }else if ([noti.userInfo[@"resultStatus"] isEqualToString:@"6001"]){
        
        if ([[self getCurrentVC] isKindOfClass:[MyOrderViewController class]]) {
            
            //            NSLog(@"属于");
        }else{
            //            NSLog(@"不属于");
            [self pushToOrderVC];
        }
        
        
    }else{
        
        [self showErrorWithString:memo];
    }
}

- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (UIViewController *)getCurrentVC {
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}


- (void)pushToMapView{
    
    ShowHUD;
    HiddenBar;
    
    MapViewController * mapVC = [MapViewController new];
    
    mapVC.merchants_latitude = [NSString stringWithFormat:@"%@",self.dict[@"merchants_latitude"]];
    mapVC.merchants_longitude = [NSString stringWithFormat:@"%@",self.dict[@"merchants_longitude"]];
    mapVC.merchants_name = [NSString stringWithFormat:@"%@",self.dict[@"merchants_name"]];
    mapVC.merchants_local = [NSString stringWithFormat:@"%@",self.dict[@"merchants_address"]];
    
    [self.navigationController pushViewController:mapVC animated:YES];
    
    HiddenHUD;
}


@end
